package org.fs;

import java.util.List;

import org.fs.dao.AirportHome;
import org.fs.dao.FsConnectionHome;
import org.fs.entities.Airport;
import org.fs.entities.FsConnection;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class ConnectionManager {

	private AirportHome airportHome;
	private FsConnectionHome connectionHome;
	private AirportAbbreviationMap airportMap;
	private SessionFactory sessionFactory;
	private String country;

	public void saveConnection(String abbFrom, String abbTo){
		
		Airport from = airportMap.get(abbFrom);
		Airport to = airportMap.get(abbTo);
		if(from == null || to == null){
			Transaction trx = sessionFactory.getCurrentSession().beginTransaction();		
			if(from == null){
				from = new Airport();
				from.setAbbreviation(abbFrom);
				airportHome.persist(from);
				airportMap.put(abbFrom, from);
			}
			if(to == null){
				to = new Airport();
				to.setAbbreviation(abbTo);
				to.setCountry(country);
				airportHome.persist(to);
				airportMap.put(abbTo, to);
			}
			trx.commit();
		}
		FsConnection conn = new FsConnection();
		conn.setAirportByAId1(from);
		conn.setAirportByAId2(to);
		Transaction trx = sessionFactory.getCurrentSession().beginTransaction();
		connectionHome.persist(conn);
		trx.commit();
		
	}
	
	public List<FsConnection> getAllConnections(){
		Transaction trx = sessionFactory.getCurrentSession().beginTransaction();
		List<FsConnection> conns = connectionHome.getAll();
		trx.commit();
		return conns;
	}

	public void setAirportHome(AirportHome airportHome) {
		this.airportHome = airportHome;
	}

	public void setConnectionHome(FsConnectionHome connectionHome) {
		this.connectionHome = connectionHome;
	}

	public void setAirportMap(AirportAbbreviationMap airportMap) {
		this.airportMap = airportMap;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void setCountry(String to) {
		country = to;
		
	}
}
